﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using Microsoft.Build.Framework;

namespace TeamDeploy.Tasks
{
    public class RemoteExecute : TaskBase
    {
        private bool waitForExit;

        public override bool Execute()
        {
            try
            {

                if (!System.IO.File.Exists(RemoteExecutePathFilename))
                {
                    Log.LogError("RemoteExecute does not exists at: " + RemoteExecutePathFilename);
                    return false;
                }

                string options = " -i 0 -s -accepteula ";
                if (OverridePSExecArgs != null && OverridePSExecArgs.Length > 0)
                {
                    options = OverridePSExecArgs;
                }


                if (!waitForExit)
                    options += "-d ";

                string args = @"\\" + TargetMachine + options + RemoteCommand + " " + OptionalParameters;



                Process p = Process.Start(RemoteExecutePathFilename, args);
                if (waitForExit)
                {
                    p.WaitForExit();

                    if (p.ExitCode != 0)
                    {
                        string message = "Executing " + RemoteCommand + " on " + TargetMachine + " returned code:" + p.ExitCode;

                        if (ignoreExitCode)
                        {
                            Log.LogMessage(message);
                        }
                        else
                        {
                            Log.LogError(message);
                            return false;
                        }
                    }
                }

                if (BuildEngine != null)
                {
                    Log.LogMessage("Executing " + RemoteCommand + " on " + TargetMachine + " completed successfully.");
                }


                return true;
            }
            catch (Exception ex)
            {
                if (BuildEngine != null)
                {
                    Log.LogError("Error executing " + RemoteCommand + " TargetMachine=" +
                                 TargetMachine + " RemoteExecutePathFilename=" + RemoteExecutePathFilename + ":::" +
                                 ex);
                }
                return false;
            }
        
        }

        [Required]
        public string TargetMachine { get; set; }

        [Required]
        public string RemoteCommand { get; set; }

        public string OptionalParameters { get; set; }

        public string WaitForExit
        {
            get { return waitForExit.ToString(); }
            set { waitForExit = bool.Parse(value); }
        }

        [Required]
        public string RemoteExecutePathFilename { get; set; }

        public string OverridePSExecArgs { get; set; }
    }
}
